'use server';
import { PrismaClient } from '@prisma/client'
import { cookies } from 'next/headers';

//预构建
// export const dynamic = 'force-dynamic';

export const action = async (formdata: FormData): Promise<LoginResponse> => {
    'use server';
    //预构建
    //  unstable_noStore();

    const username = formdata.get('username');
    const password = formdata.get('password');

    if (!username || !password) {
        throw new Error('Username or password is missing');
    }

    await new Promise((res) => setTimeout(() => res(null), 2 * 1000));

    const prisma = new PrismaClient();
    const user = await prisma.user.create({
        data: {
            username: username.toString(),
            password: password.toString(),
        },
    });

    if (user) {
        return {
            code: 0,
            msg: '',
        };

    } else {
        return {
            code: 1,
            msg: '注册失败, 请联系管理员',
        };
    }
}

export const action1 = async (formdata: FormData): Promise<LoginResponse> => {

    const username = formdata.get('username');
    const password = formdata.get('password');

    if (!username || !password) {
        throw new Error('Username or password is missing');
    }

    const prisma = new PrismaClient()
    const userDatas = await prisma.user.findMany();
    const hasObject = userDatas.some(user => user.username == username && user.password == password);

    if (hasObject) {
        const token = btoa(JSON.stringify({
            username,
        }));

        cookies().set({
            name: 'username',
            value: username?.toString() || '',
            maxAge: 120,
            httpOnly: true,
        });

        cookies().set({
            name: 'token',
            value: token,
            maxAge: 120,
            httpOnly: true,
        });

        return {
            code: 0,
            msg: '',
        };

    } else {
        return {
            code: 1,
            msg: '登录失败, 请联系管理员',
        };
    }
}

export const action2 = async (formdata: FormData): Promise<LoginResponse> => {

    const theme = formdata.get('theme');

    const prisma = new PrismaClient();
    const data = {
        user_id: 1,
        theme: theme?.toString(),
    };

    const post = await prisma.user_setting.update({
        where: { id: 1 },
        data: {
            ...data,
        },
    });

    if (post) {
        return {
            code: 0,
            msg: '',
        };

    } else {
        return {
            code: 1,
            msg: '添加失败, 请联系管理员',
        };
    }
}

